package com.flightgame.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.flightgame.hibernate.FlightDao;
import com.flightgame.hibernate.Message;
import com.flightgame.hibernate.MessageDao;
import com.flightgame.hibernate.OwnershipDao;
import com.flightgame.hibernate.User;
import com.flightgame.hibernate.UserDao;
import com.flightgame.tools.Utils;

@Service
public class MessageServices {
	@Autowired
	public FlightDao flightDao;
	@Autowired
	public UserDao userDao;
	@Autowired
	public Utils utils;
	@Autowired
	public MessageDao messageDao;
	@Autowired
	public OwnershipDao ownershipDao;
	
	public int createNewMessage(String senderId,String receiverId,String isFlight,String messageText){
		Message message = new Message();
		try{
			int sender = Integer.parseInt(senderId);
			int receiver = Integer.parseInt(receiverId);
			boolean isFlightMessage = Boolean.parseBoolean(isFlight);
			String receiveUser;
			
			if(isFlightMessage == true){
				if(ownershipDao.getOwnership(sender) == null || ownershipDao.getOwnership(receiver) == null) return utils.NO_OWNERSHIP_WITH_ID;
				receiveUser = ownershipDao.getOwnership(receiver).getUsername();
			}
			else{
				if(userDao.getUserWithId(sender) == null || userDao.getUserWithId(receiver) == null) return utils.NO_USER;
				receiveUser = userDao.getUserWithId(receiver).getUsername();
			}
			
			message.setSendid(sender);
			message.setReceiveid(receiver);
			message.setIsflightmsg(isFlightMessage);
			message.setMessage(messageText);
			message.setReceivername(receiveUser);
			messageDao.createMessage(message);
		}
		catch(NumberFormatException n){
			return utils.INVALID_NUMBER_FORMAT;
		}
		return utils.SUCCESS;
	}
}
